#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复微信客服会话状态问题
在发送消息前自动建立会话
"""

import os
import sys
import logging
from dotenv import load_dotenv

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from config.settings import settings
from services.wx_api import WeChatAPI

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def add_establish_session_method():
    """为WeChatAPI类添加建立会话的方法"""
    
    # 读取原始文件
    with open('services/wx_api.py', 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 检查是否已经存在establish_session方法
    if 'def establish_session(' in content:
        print("✅ establish_session方法已存在")
        return
    
    # 在check_session_status方法后添加establish_session方法
    establish_session_method = '''
    def establish_session(self, open_kfid, external_userid, token=None):
        """
        建立客服会话
        
        Args:
            open_kfid: 客服账号ID
            external_userid: 外部用户ID
            token: access_token
            
        Returns:
            bool: 是否成功建立会话
        """
        try:
            if not token:
                token = self.get_access_token()
            if not token:
                logger.error("无法获取access_token")
                return False
            
            url = "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/trans"
            params = {'access_token': token}
            data = {
                'external_userid': external_userid,
                'open_kfid': open_kfid,
                'service_state': 1  # 1表示接待中
            }
            
            logger.info(f"🔄 尝试建立会话...")
            logger.info(f"   external_userid: {external_userid}")
            logger.info(f"   open_kfid: {open_kfid}")
            
            response = self.session.post(url, params=params, json=data, timeout=10)
            result = response.json()
            
            if result.get('errcode') == 0:
                logger.info(f"✅ 会话建立成功")
                return True
            else:
                logger.error(f"❌ 会话建立失败: {result}")
                return False
                
        except Exception as e:
            logger.error(f"❌ 建立会话异常: {str(e)}")
            return False
'''
    
    # 找到check_session_status方法的结束位置
    check_method_end = content.find('    def send_kf_message(')
    if check_method_end == -1:
        print("❌ 无法找到send_kf_message方法位置")
        return
    
    # 插入establish_session方法
    new_content = content[:check_method_end] + establish_session_method + content[check_method_end:]
    
    # 写回文件
    with open('services/wx_api.py', 'w', encoding='utf-8') as f:
        f.write(new_content)
    
    print("✅ 已添加establish_session方法")

def update_send_kf_message_method():
    """更新send_kf_message方法，添加自动会话建立逻辑"""
    
    # 读取文件
    with open('services/wx_api.py', 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 查找send_kf_message方法
    start_marker = '    def send_kf_message(self, open_kfid, external_userid, msg_type, content, token=None):'
    start_pos = content.find(start_marker)
    
    if start_pos == -1:
        print("❌ 无法找到send_kf_message方法")
        return
    
    # 找到方法开始后的会话状态检查部分
    session_check_start = content.find('# 先检查会话状态', start_pos)
    if session_check_start == -1:
        print("❌ 无法找到会话状态检查部分")
        return
    
    # 找到会话状态检查的结束位置
    session_check_end = content.find('url = "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg"', session_check_start)
    if session_check_end == -1:
        print("❌ 无法找到发送消息URL")
        return
    
    # 构建新的会话状态检查逻辑
    new_session_check = '''            # 先检查会话状态
            session_status = self.check_session_status(open_kfid, external_userid, token)
            if session_status and session_status.get('errcode') == 0:
                service_state = session_status.get('service_state', 0)
                logger.info(f"📊 当前会话状态: {service_state}")
                
                # 如果会话状态不是1（接待中）或3（转接中），尝试建立会话
                if service_state not in [1, 3]:
                    logger.warning(f"⚠️ 会话状态不正确 ({service_state})，尝试建立会话")
                    if not self.establish_session(open_kfid, external_userid, token):
                        logger.error("❌ 无法建立会话，发送消息失败")
                        return None
                    logger.info("✅ 会话建立成功，继续发送消息")
                elif service_state == 3:
                    logger.info(f"📤 会话状态为转接中 ({service_state})，继续发送消息")
'''
    
    # 替换会话状态检查部分
    new_content = content[:session_check_start] + new_session_check + content[session_check_end:]
    
    # 写回文件
    with open('services/wx_api.py', 'w', encoding='utf-8') as f:
        f.write(new_content)
    
    print("✅ 已更新send_kf_message方法")

def test_fix():
    """测试修复效果"""
    print("\n🧪 测试修复效果...")
    
    load_dotenv()
    os.environ['WX_CORPID'] = settings.WX_CORPID
    os.environ['WX_CORPSECRET'] = settings.WX_CORPSECRET
    
    wx_api = WeChatAPI()
    access_token = wx_api.get_access_token()
    
    if not access_token:
        print("❌ 无法获取access_token")
        return
    
    open_kfid = settings.OPEN_KF_ID
    external_userid = "wmtI2SEAAAvOQbOUmj28OCNdTYqYIaYw"
    
    # 测试建立会话
    print("测试建立会话...")
    if hasattr(wx_api, 'establish_session'):
        success = wx_api.establish_session(open_kfid, external_userid, access_token)
        if success:
            print("✅ 会话建立测试成功")
        else:
            print("❌ 会话建立测试失败")
    else:
        print("❌ establish_session方法不存在")
    
    # 测试发送消息
    print("测试发送消息...")
    result = wx_api.send_kf_message(open_kfid, external_userid, 'text', '测试消息', access_token)
    if result:
        print("✅ 消息发送测试成功")
    else:
        print("❌ 消息发送测试失败")

def main():
    """主函数"""
    print("🚀 修复微信客服会话状态问题")
    print("=" * 50)
    
    # 添加establish_session方法
    print("1. 添加establish_session方法...")
    add_establish_session_method()
    
    # 更新send_kf_message方法
    print("\n2. 更新send_kf_message方法...")
    update_send_kf_message_method()
    
    # 测试修复效果
    print("\n3. 测试修复效果...")
    test_fix()
    
    print("\n🎯 修复完成!")
    print("现在系统会在发送消息前自动建立会话")

if __name__ == '__main__':
    main() 